<template>
  <div class="addMaintainPlan zy-content">
    <back-level :goPage="back" />
    <Card :title="planType" class="detail-content-layout">
      <div class="line-title">
        <Steps :current="current" class="steps">
          <Step :title="`${$t('选择盘点对象') }`"></Step>
          <Step :title="`${$t('创建盘点时间') }`"></Step>
        </Steps>
      </div>
      <!-- 第一步 -->
      <div class="searchBox" v-if="current === 0">
        <Form ref="stepOneValidate" :rules="stepOneRuleValidate" :model="formInline">
          <div class="labelTop">
            <FormItem :label="`${$t('盘点计划')}`" class="item " prop="backupPlanName">
              <Input type="text" v-model="formInline.backupPlanName" :placeholder="`${$t('common.inputInfo')}`" clearable></Input>
              <Input style="display:none"></Input>
            </FormItem>
          </div>
        </Form>
        <div class="addDev">
          <span @click="addDev()">
            <Icon type="md-add-circle" size="20" />
            {{ $t('添加盘点物料') }}
          </span>
        </div>
        <div class="tableContent">
          <Table border class="resizable-table" @on-column-width-resize="onColumnWidthResize" :columns="columns" :data="dataArr">
            <template slot-scope="{ row }" slot="action">
              <span class="operationBtn" @click="deleteDevRow(row)">{{ $t('common.Delete') }}</span>
            </template>
          </Table>
        </div>
        <Modal :mask-closable="false" v-model="addDevVisible" :title="`${$t('盘点物料')}`" width="1400" class="modal-content-layout">
          <Form label-position="top">
            <Row :gutter="16">
              <Col span="6">
              <FormItem :label="`${$t('common.WarehouseNo')}`">
                <Select v-model="addDevpageParams.backupConfigId" filterable clearable @on-change="getShelfList">
                  <Option v-for="(item) of backupList" :value="item.id" :key="item.id" :label="item.backupNo+'-'+item.backupName"></Option>
                </Select>
              </FormItem>
              </Col>
              <Col span="6">
              <FormItem :label="`${$t('spareParts.ReservoirNo')}`">
                <Select v-model="addDevpageParams.shelfConfigId" filterable clearable @on-change="getLocationList">
                  <Option v-for="(item) of shelfList" :value="item.id" :key="item.id" :label="item.shelfNo+'-'+item.shelf"></Option>
                </Select>
              </FormItem>
              </Col>
              <Col span="6">
              <FormItem :label="`${$t('spareParts.LocationNo')}`">
                <Select v-model="addDevpageParams.locationConfigId" filterable clearable>
                  <Option v-for="(item) of locationList" :value="item.id" :key="item.id" :label="item.locationNo+'-'+item.location"></Option>
                </Select>
              </FormItem>
              </Col>
              <Col span="6">
              <FormItem :label="`${$t('物料编号')}`">
                <Input type="text" v-model="addDevpageParams.backupNo" clearable :placeholder="`${$t('common.inputInfo')}`"></Input>
              </FormItem>
              </Col>
              <Col span="6">
              <FormItem :label="`${$t('物料名称')}`">
                <Input type="text" v-model="addDevpageParams.goodsName" clearable :placeholder="`${$t('common.inputInfo')}`"></Input>
              </FormItem>
              </Col>
              <Col span="6">
              <FormItem :label="`${$t('规格型号')}`">
                <Input type="text" v-model="addDevpageParams.specification" clearable :placeholder="`${$t('common.inputInfo')}`"></Input>
              </FormItem>
              </Col>
              <Col span="6">
              <FormItem :label="`${$t('备件分类')}`">
                <Select v-model="addDevpageParams.sparePartsVal" filterable clearable @on-change="handleChange">
                  <Option v-for="(item) of sparePartsList" :value="item.label" :key="item.label" :label="item.value"></Option>
                </Select>
              </FormItem>
              </Col>
              <Col span="6">
              <Button style="position:relative;top:12px;" class="ivu-btn-lg" type="primary" @click="changeNum">{{ $t('common.Query') }}</Button>
              </Col>
            </Row>
          </Form>
          <div>
            <Table border class="resizable-table" @on-column-width-resize="onColumnWidthResize" :columns="addDevcolumns" :data="addDevdata"
                   @on-selection-change="handleSelectionChange"></Table>
            <div class="pageWrap mt16">
              <Page :total="total" :page-size="addDevpageParams.pageSize" :page-size-opts="$variable.pageSizes" :current="addDevpageParams.pageNum"
                    @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total />
            </div>
          </div>
          <div slot="footer">
            <Button type="default" @click="addDevCancel">{{ $t('common.Cancle') }}</Button>
            <Button type="primary" @click="addDevOk">{{ $t('maintenance.Confirmed') }}</Button>
          </div>
        </Modal>
      </div>
      <!-- 第二步 -->
      <div v-if="current === 1" class="second">
        <Form ref="stepTwoValidate" :rules="ruleValidate" :model="stepTwoValidate">
          <Row>
            <Col span="8">
            <Col>
            <FormItem :label="`${$t('盘点方式')}`">
              <Input type="text" :value="$t('定期盘点')" disabled></Input>
            </FormItem>
            </Col>
            <Col>
            <Row>
              <Col span="16">
              <FormItem prop="triggerInterval" :label="`${$t('maintenance.TriggerInterval')}`">
                <InputNumber style="width:100%" :min="0" :max="999" v-model="stepTwoValidate.triggerInterval" :placeholder="`${$t('common.inputInfo')}`"></InputNumber>
              </FormItem>
              </Col>
              <Col span="8" style="position:relative;top:39px">
              <FormItem prop="triggerCycle">
                <Select v-model="stepTwoValidate.triggerCycle" clearable>
                  <Option v-for="item in cycle" :key="item.key" :value="item.key" :label="item.name"></Option>
                </Select>
              </FormItem>
              </Col>
            </Row>
            </Col>
            <Col>
            <FormItem :label="`${$t('maintenance.createTime')}`" class="item" prop="firstTime">
              <DatePicker type="datetime" :options="options" v-model="stepTwoValidate.firstTime"></DatePicker>
            </FormItem>
            </Col>
            <Col>
            <FormItem :label="`${$t('maintenance.planEndTime')}`" class="item" prop="planEndTime">
              <DatePicker type="datetime" :options="options1" v-model="stepTwoValidate.planEndTime">
              </DatePicker>
            </FormItem>
            </Col>
            </Col>
          </Row>
        </Form>
      </div>
      <div class="nextBtn">
        <Button @click="previous" v-if="current !== 0">{{ $t('common.Pre') }}</Button>
        <Button type="primary" @click="next" v-if="current !== 1">{{ $t('common.Next') }}</Button>
        <Button type="primary" :loading="loading" @click="create" v-if="current === 1">{{ $t('common.Creatingsuccessful') }}</Button>
      </div>
    </Card>
  </div>
</template>

<script>
import toggleTableOperation from '@/mixins/toggleTableOperation'
import { getBackup, getShelf, getLocation } from '@/api/index.js'
export default {
  name: 'addMaintainPlan',
  mixins: [toggleTableOperation],
  components: {},
  props: ['editId', 'planType'],
  data() {
    return {
      sparePartsList: [
        {
          label: 'AV',
          value: 'AV类'
        },
        {
          label: 'AE',
          value: 'AE类'
        },
        {
          label: 'AD',
          value: 'AD类'
        },
        {
          label: 'BV',
          value: 'BV类'
        },
        {
          label: 'BE',
          value: 'BE类'
        },
        {
          label: 'BD',
          value: 'BD类'
        },
        {
          label: 'CV',
          value: 'CV类'
        },
        {
          label: 'CE',
          value: 'CE类'
        },
        {
          label: 'CD',
          value: 'CD类'
        }
      ],
      selectData: [],
      current: 0,
      loading: false,
      addDevVisible: false,
      searchParams: {},
      formInline: {
        backupPlanName: ''
      },
      stepOneRuleValidate: {
        backupPlanName: [{ required: true, message: this.$t('common.inputInfo'), trigger: 'blur' }]
      },
      stepTwoValidate: {
        triggerInterval: null,
        triggerCycle: '',
        firstTime: this.$moment(new Date()).format('YYYY-MM-DD HH:00:00'),
        planEndTime: this.$moment(new Date()).format('YYYY-MM-DD HH:00:00')
      },
      options: {},
      options1: {
        disabledDate: date => {
          let data = this.stepTwoValidate.firstTime ? this.stepTwoValidate.firstTime : ''
          return date && date.valueOf() <= new Date(data).valueOf()
        }
      },
      ruleValidate: {
        triggerInterval: [{ required: true, type: 'number', message: this.$t('common.inputInfo'), trigger: 'blur' }],
        triggerCycle: [{ required: true, type: 'number',message: this.$t('common.selectInfo'), trigger: 'change' }],
        firstTime: [{ required: true, message: this.$t('common.selectInfo') }],
        planEndTime: [{ required: true, message: this.$t('common.selectInfo') }]
      },
      columns: [
        {
          type: 'index',
          width: 80,
          title: `${this.$t('common.index')}`,
          align: 'center',
          resizable: true
        },
        {
          title: `${this.$t('spareParts.Warehouse')}`,
          key: 'warehouseName',
          minWidth: 120,
          align: 'center',
          type: 'select',
          resizable: true
        },
        {
          title: `${this.$t('spareParts.Rack')}`,
          key: 'shelfConfigName',
          minWidth: 100,
          align: 'center',
          type: 'select',
          resizable: true
        },
        {
          title: `${this.$t('spareParts.Location')}`,
          key: 'locationConfigName',
          minWidth: 100,
          align: 'center',
          type: 'select',
          resizable: true
        },
        {
          title: `${this.$t('common.SpareNumber')}`,
          key: 'backupNo',
          minWidth: 160,
          align: 'center',
          type: 'input',
          resizable: true
        },
        {
          title: `${this.$t('common.GoodsName')}`,
          key: 'goodsName',
          minWidth: 160,
          align: 'center',
          type: 'input',
          resizable: true
        },
        {
          title: `${this.$t('spareParts.Specification')}`,
          key: 'specification',
          minWidth: 120,
          align: 'center',
          type: 'input',
          resizable: true
        },
        {
          title: `${this.$t('common.SpareClassification')}`,
          key: 'location',
          minWidth: 160,
          align: 'center',
          type: 'select',
          render: (h, params) => {
            return h('div', params.row.sparePartsABC + params.row.sparePartsVED)
          },
          resizable: true
        },
        {
          title: `${this.$t('spareParts.quantity')}`,
          key: 'quantityInStock',
          minWidth: 100,
          align: 'center',
          type: 'input',
          resizable: true
        },
        { title: `${this.$t('common.operation')}`, slot: 'action', align: 'center', minWidth: 100 }
      ],
      addDevcolumns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: `${this.$t('spareParts.Warehouse')}`,
          key: 'warehouseName',
          minWidth: 120,
          align: 'center',
          type: 'select',
          resizable: true
        },
        {
          title: `${this.$t('spareParts.Rack')}`,
          key: 'shelfConfigName',
          minWidth: 100,
          align: 'center',
          type: 'select',
          resizable: true
        },
        {
          title: `${this.$t('spareParts.Location')}`,
          key: 'locationConfigName',
          minWidth: 100,
          align: 'center',
          type: 'select',
          resizable: true
        },
        {
          title: `${this.$t('common.SpareNumber')}`,
          key: 'backupNo',
          minWidth: 160,
          align: 'center',
          type: 'input',
          resizable: true
        },
        {
          title: `${this.$t('common.GoodsName')}`,
          key: 'goodsName',
          minWidth: 160,
          align: 'center',
          type: 'input',
          resizable: true
        },
        {
          title: `${this.$t('spareParts.Specification')}`,
          key: 'specification',
          minWidth: 130,
          align: 'center',
          type: 'input',
          resizable: true
        },
        {
          title: `${this.$t('common.SpareClassification')}`,
          key: 'location',
          minWidth: 180,
          align: 'center',
          type: 'select',
          render: (h, params) => {
            return h('div', params.row.sparePartsABC + params.row.sparePartsVED)
          },
          resizable: true
        },
        {
          title: `${this.$t('spareParts.quantity')}`,
          key: 'quantityInStock',
          minWidth: 100,
          align: 'center',
          type: 'input',
          resizable: true
        }
      ],
      addDevdata: [],
      dataArr: [],
      cycle: [
        { name: this.$t('月度'), key: 3 },
        { name: this.$t('季度'), key: 4 },
        { name: this.$t('半年度'), key: 5 },
        { name: this.$t('年度'), key: 6 }
      ],
      addDevpageParams: {
        pageSize: 10,
        pageNum: 1
      },
      total: 0,
      backupList: [],
      shelfList: [],
      locationList: []
    }
  },
  created() {
    this.getColumnWidth(this.columns)
    if (this.editId) {
      this.getPlanDetail(this.editId)
    }
  },
  mounted() {},
  methods: {
    handleChange(val) {
      if (val) {
        this.addDevpageParams.sparePartsABC = val[0]
        this.addDevpageParams.sparePartsVED = val[1]
      } else {
        this.addDevpageParams.sparePartsABC = ''
        this.addDevpageParams.sparePartsVED = ''
      }
    },
    //获取仓库
    async getBackupList() {
      const { code, data } = await getBackup({})
      if (code === 200) {
        this.backupList = data
      }
    },
    //获取货架下拉列表
    async getShelfList(item) {
      this.shelfList = []
      this.locationList = []
      delete this.addDevpageParams.shelfIds
      delete this.addDevpageParams.locationIds
      if (!item) {
        return
      }
      let params = {}
      params.delIds = []
      params.delIds.push(item)
      const { code, data } = await getShelf(params)
      if (code === 200) {
        this.shelfList = data
      }
    },
    //获取库位下拉列表
    async getLocationList(item) {
      this.locationList = []
      delete this.addDevpageParams.locationIds
      if (!item) {
        return
      }
      let params = {}
      params.delIds = []
      params.delIds.push(item)
      const { code, data } = await getLocation(params)
      if (code === 200) {
        this.locationList = data
      }
    },
    back() {
      this.$emit('addPlan', false, {}, '')
    },
    getPlanDetail(id) {
      this.axios({
        method: 'get',
        url: '/dms/dmsBackupPlan/queryById',
        params: {
          id
        }
      }).then(async res => {
        if (res.code === 200) {
          this.formInline = {
            backupPlanName: this.planType == this.$t('编辑盘点计划') ? res.data.backupPlanName : ''
          }
          this.stepTwoValidate = {
            triggerInterval: res.data.triggerInterval,
            triggerCycle: res.data.triggerCycle,
            firstTime: res.data.firstTime,
            planEndTime: res.data.planEndTime
          }
          this.dataArr = res.data.backupPlanBookVoList
        } else {
          this.$Message.warning({ content: res.msg, duration: 6, closable: true })
        }
      })
    },
    next() {
      if (this.current == 0) {
        this.$refs['stepOneValidate'].validate(valid => {
          if (valid) {
            if (!this.dataArr.length) {
              this.$Message.warning({ content: this.$t('请添加盘点物料！'), duration: 6, closable: true })
              return false
            }
            this.axios({
              method: 'get',
              url: '/dms/dmsBackupPlan/validPlanName',
              params: {
                id: this.editId,
                planName: this.formInline.backupPlanName
              }
            }).then(res => {
              if (res.code == 200) {
                this.current += 1
              } else {
                this.$Message.warning({ content: res.msg, duration: 6, closable: true })
              }
            })
          } else {
            return
          }
        })
      }
    },
    previous() {
      this.current -= 1
    },
    create() {
      this.$refs.stepTwoValidate.validate(valid => {
        if (valid) {
          const firstTimeinfo = new Date(this.stepTwoValidate.firstTime).getTime()
          const nowTime = new Date().getTime()
          if (Number(firstTimeinfo) < Number(nowTime)) {
            this.$Message.warning({ content: this.$t('首次生成时间必须大于当前时间！'), duration: 6, closable: true })
            return
          }
          if (new Date(this.stepTwoValidate.firstTime).getTime() >= new Date(this.stepTwoValidate.planEndTime).getTime()) {
            this.$Message.warning({ content: this.$t('首次生成时间不得大于计划截止时间！'), duration: 6, closable: true })
            return
          }
          this.loading = true
          const firstTime = this.$moment(this.stepTwoValidate.firstTime).format('YYYY-MM-DD HH:mm:00')
          const planEndTime = this.$moment(this.stepTwoValidate.planEndTime).format('YYYY-MM-DD HH:mm:00')
          const backupPlanBookIds = this.dataArr.map(item => {
            return item.id
          })
          let data = {
            triggerCycle: this.stepTwoValidate.triggerCycle,
            triggerInterval: this.stepTwoValidate.triggerInterval,
            backupPlanName: this.formInline.backupPlanName,
            firstTime,
            planEndTime,
            backupPlanBookIds
          }
          if (!this.editId || this.planType == this.$t('复制盘点计划')) {
            this.axios({
              method: 'post',
              url: '/dms/dmsBackupPlan/add',
              data
            })
              .then(res => {
                if (res.code === 200) {
                  this.$emit('addPlan', false, {}, '')
                  this.$Message.success(res.msg)
                } else {
                  this.$Message.warning({ content: res.msg, duration: 6, closable: true })
                }
              })
              .finally(() => {
                this.loading = false
              })
          } else {
            let params = {
              ...data,
              id: this.editId
            }
            this.axios({
              method: 'put',
              url: '/dms/dmsBackupPlan/edit',
              data: params
            })
              .then(res => {
                if (res.code === 200) {
                  this.$emit('addPlan', false, {}, '')
                  this.$Message.success(res.msg)
                } else {
                  this.$Message.warning({ content: res.msg, duration: 6, closable: true })
                }
              })
              .finally(() => {
                this.loading = false
              })
          }
        } else {
          return
        }
      })
    },
    addDev() {
      this.getColumnWidth(this.addDevcolumns)
      this.addDevcolumns.reverse().reverse()
      this.addDevVisible = true
      this.$forceUpdate()
      this.searchList()
      this.getBackupList()
    },
    handleSelectionChange(selectionData) {
      let arr = [...selectionData]
      this.selectData = arr
    },
    addDevCancel() {
      this.addDevVisible = false
      this.selectData = []
    },
    addDevOk() {
      const arr = this.dataArr.filter(item => this.selectData.some(x => x.id == item.id))
      if (arr.length) {
        this.$Message.warning({ content: this.$t('有重复数据，请重新选择！'), duration: 6, closable: true })
        return false
      }
      this.addDevVisible = false
      this.dataArr = [...this.dataArr, ...this.selectData]
      this.selectData = []
    },
    //分页
    changeNum() {
      this.addDevpageParams.pageNum = 1
      this.searchList()
    },
    changePageSize(val) {
      this.addDevpageParams.pageSize = val
      this.searchList()
    },
    changePageNum(val) {
      this.addDevpageParams.pageNum = val
      this.searchList()
    },
    searchList() {
      let data = { ...this.addDevpageParams }
      this.axios({
        method: 'post',
        url: '/dms/standingBook/list',
        data
      }).then(res => {
        if (res.code === 200) {
          this.addDevdata = res.data.list
          this.total = res.data.total
        } else {
          this.$Message.warning({ content: res.msg, duration: 6, closable: true })
        }
      })
    },
    deleteDevRow(row) {
      this.dataArr = this.dataArr.filter(item => item.id != row.id)
    }
  }
}
</script>

<style lang="scss">
.addMaintainPlan {
  background: #fff;
  .line-title {
    display: flex;
    justify-content: flex-start;
    font-size: 20px;
    padding: 10px;
    align-items: center;
    position: absolute;
    top: 3px;
    right: 0;
    .ivu-steps .ivu-steps-head .ivu-steps-item.ivu-steps-status-process .ivu-steps-title {
      background: transparent;
    }
    .ivu-steps .ivu-steps-title {
      background: transparent;
      vertical-align: sub;
    }
    .back {
      color: #187bdb;
      font-size: 16px;
      padding-left: 20px;
      cursor: pointer;
    }
    .steps {
      width: auto;
      margin-left: auto;
    }
  }
  .searchBox {
    .addDev {
      padding: 10px 0;
      span {
        font-size: 16px;
        cursor: pointer;
      }
    }
    .labelTop {
      display: flex;
      border-bottom: 2px solid #d7d7d7;
      .item {
        width: 27%;
      }
    }
    .label {
      display: flex;
      .item {
        margin-left: 10px;
      }
    }
  }
  .nextBtn {
    text-align: center;
    padding: 50px 0px;
    button {
      margin: 10px;
    }
  }
}
</style>
